#include "KnifeThrowingEnemy.h"
#include "Game.h"
#include "Projectile.h"

KnifeThrowingEnemy::KnifeThrowingEnemy(SpawnInfo spawnInfo) : Enemy(spawnInfo)
{
	knifeImage = new Image("images/knife.bmp", COL_KEY);
	knifeImage->setRefCentre();

	images[STANDING] = new Image("images/knife_thrower/standing.bmp", COL_KEY);
	images[STANDING]->setRefBottomCentre();

	images[WALKING] = new Animation("images/knife_thrower/walking.bmp", 4, 100, COL_KEY);
	images[WALKING]->setRefBottomCentre();

	Animation* temp = new Animation("images/knife_thrower/throwing.bmp", 4, 50, COL_KEY);
	temp->setLooping(false);
	images[THROWING] = temp;
	images[THROWING]->setRefBottomCentre();

	images[DEAD] = new Image("images/knife_thrower/dead.bmp", COL_KEY);
	images[DEAD]->setReferencePoint(images[DEAD]->getWidth()/2, images[DEAD]->getHeight() - 5);

	state = STANDING;

	throwTime = SDL_GetTicks();
}

KnifeThrowingEnemy::~KnifeThrowingEnemy()
{
	//TODO: Release knife image when I've made sure it doesn't break projectiles
	//delete knifeImage;

	for(int i=0; i<NUM_STATES; i++){
		if( images[i] != NULL ) delete images[i];
	}
}

void KnifeThrowingEnemy::tick()
{
	if(!alive){
		state = DEAD;
		return;
	}

	if(u != 0) return;

	Player* p = Game::getInstance()->getPlayer();

	flipped = (p->getX() < x);

	int distance = abs(p->getX() - x);

	if(state == THROWING)
	{
		if(((Animation*) images[THROWING])->getPlayCount() >= 1)
		{
			Game::getInstance()->addEntity(
				new Projectile(this, knifeImage, x, y+40, flipped ? -5.0f : 5.0f, 0.0f, 25, false)
			);

			throwTime = SDL_GetTicks() + 2000;
			state = STANDING;
		}
		return;
	}

	if( advance(120) )
	{
		if(state != STANDING)
		{
			throwTime = SDL_GetTicks() + 2000;
			state = STANDING;
		}
		else
		{
			if(SDL_GetTicks() > throwTime)
			{
				state = THROWING;
				((Animation*) images[THROWING])->start();
			}
		}
	}
	else
	{
		state = WALKING;
	}
}

Image* KnifeThrowingEnemy::getCurrentImage()
{
	return images[state];
}
